<template>
  <div>
    <!-- <h1 class="title">防护设置</h1> -->
    <div
      class="setting-box content outreach-box"
      v-loading="loading"
      element-loading-background="rgba(0, 0, 0, 0.1)"
    >
      <div style="display: flex; align-items: center">
        <div class="leftCont">数据防护</div>
        <div>
          <el-switch
            v-model="data.data_def"
            active-value="1"
            inactive-value="0"
            :disabled="treeStore.isShowStrategyDetail"
          >
          </el-switch>
          <span class="promptFont">注：数据防护中目录防护最多可以添加3条</span>
        </div>
      </div>
      <div style="display: flex; margin-top: 19px">
        <div class="leftCont"></div>
        <div style="display: flex; align-items: center">
          <div class="baseDiv">
            <span v-for="(value, index) in data.dir_def" :key="index" class="spanSty">
              <span style="margin-right: 5px">{{ value }}</span>
              <el-icon
                style="cursor: pointer"
                :style="{
                  'pointer-events': treeStore.isShowStrategyDetail ? 'none' : 'all',
                }"
                @click="delPath(index)"
                ><CircleClose
              /></el-icon>
              <br />
            </span>
          </div>
          <div class="diySty">
            <el-button
              @click="treeStore.directoryDialogVModel = true"
              :disabled="data.dir_def.length >= 3 || treeStore.isShowStrategyDetail"
              >浏览目录</el-button
            >
          </div>
        </div>
      </div>
      <template v-if="treeStore.osType === 'linux'">
        <div style="display: flex; margin-top: 11px">
          <div class="leftCont"></div>
          <div class="promptFont">
            例外应用程序或类型（保护目录下可以写入的文件或文件类型）
          </div>
        </div>
        <div style="display: flex; margin: 13px 0 0 125px; flex-direction: column">
          <div>
            <el-input
              v-model="linexInput"
              style="width: 400px"
              @input="fileErrTip = ''"
              :placeholder="
                fileType === '0' ? '请输入文件名(可带后缀)' : '请输入后缀名(例如.log)'
              "
              class="input-with-select"
              :disabled="treeStore.isShowStrategyDetail"
            >
              <template #prepend>
                <el-select
                  v-model="fileType"
                  placeholder="请选择类型"
                  class="font-16"
                  style="width: 115px"
                  :disabled="treeStore.isShowStrategyDetail"
                >
                  <el-option label="文件名" :value="'0'" />
                  <el-option label="后缀名" :value="'1'" />
                </el-select>
              </template>
              <template #append>
                <el-button :icon="Plus" @click="addSelect" />
              </template>
            </el-input>
          </div>
          <div style="height: 20px; line-height: 20px">
            <span v-show="fileErrTip" class="file-type-err">{{ fileErrTip }}</span>
          </div>
        </div>

        <div style="display: flex">
          <div class="leftCont"></div>
          <div class="baseDiv">
            <span
              v-for="(value, index) in data.except_app_type"
              :key="index"
              class="spanSty"
            >
              <span style="margin-right: 5px">{{ value }}</span>
              <el-icon
                style="cursor: pointer"
                :style="{
                  'pointer-events': treeStore.isShowStrategyDetail ? 'none' : 'all',
                }"
                @click="delSelect(index)"
                ><CircleClose
              /></el-icon>
              <br />
            </span>
          </div>
        </div>
      </template>
      <template v-if="treeStore.osType === 'win'">
        <div style="display: flex; margin-top: 11px">
          <div class="leftCont"></div>
          <div class="promptFont">
            例外应用程序文件类型（保护目录下可以写入的文件类型，格式TXT,LOG,XML）
          </div>
        </div>
        <div style="display: flex; margin-top: 13px">
          <div class="leftCont"></div>
          <div style="display: flex">
            <el-select
              v-model="data.except_app_type"
              multiple
              placeholder="请选择应用程序文件类型"
              :disabled="data.dir_def.length < 1 || treeStore.isShowStrategyDetail"
            >
              <el-option
                v-for="item in fileTypeOptions"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
    </div>
    <DirectoryDialog
      :urlType="1"
      :dirFlag="true"
      :multipleChoice="true"
      :os="treeStore.osType"
      @handleDialogButton="chooseProDir"
    ></DirectoryDialog>
  </div>
</template>
<script setup>
import { ref, reactive, watch, nextTick, computed } from "vue";
import { useTreeStore } from "~/utils/pinia/tree.js";
import {
  req_getFileProtectConfig,
  req_setFileProtectConfig,
} from "~/utils/axios/index.js";
import { ElMessage } from "element-plus";
import { CircleClose } from "@element-plus/icons-vue";
import { _debounce } from "~/utils/common/function.js";
import { eventBus } from "~/utils/common/eventBus.js";
import { Plus } from "@element-plus/icons-vue";
eventBus.on("getStrategyDetail", (detail) => {
  treeStore.openTreeFlag = false;
  setData(detail.data);
});
const treeStore = useTreeStore();
treeStore.openTree();
const loading = ref(false);
const fileType = ref("0");
const linexInput = ref("");
const data = ref({
  data_def: "",
  dir_def: [],
  except_app_type: [],
});
const fileTypeOptions = ref(["TXT", "LOG", "XML"]);
const fileErrTip = ref("");
watch(
  () => treeStore.treeDeviceId,
  () => {
    getFileProtectionConfig();
    flag.value = false;
  }
);
const addSelect = () => {
  if (linexInput.value === "" && fileType.value === "0") {
    fileErrTip.value = "请输入文件名";
    return;
  }
  if (linexInput.value === "" && fileType.value === "1") {
    fileErrTip.value = "请输入后缀名";
    return;
  }
  if (fileType.value === "1" && !linexInput.value.includes(".")) {
    fileErrTip.value = "请输入合法后缀名";
    return;
  }
  data.value.except_app_type.push(linexInput.value);
  linexInput.value = "";
};
const delSelect = (index) => {
  data.value.except_app_type.splice(index, 1);
};
const chooseProDir = (ref, pathArr) => {
  data.value.dir_def = data.value.dir_def.concat(pathArr);
};
const getFileProtectionConfig = async () => {
  if (!treeStore.treeDeviceId) return;
  loading.value = true;
  data.value = {
    data_def: "",
    dir_def: [],
    except_app_type: [],
  };
  let params = Object.keys(data.value);
  try {
    const { data: res } = await req_getFileProtectConfig(treeStore.treeDeviceId, params);
    loading.value = false;
    if (res.status && res.data.length) {
      setData(res.data);
      nextTick(() => {
        flag.value = true;
      });
    }
  } catch (err) {
    loading.value = false;
  }
};
const setData = (list) => {
  let obj = {};
  list.map((item) => {
    obj = Object.assign(obj, item);
  });
  let splitStr = treeStore.osType === "linux" ? "," : ";";
  obj.dir_def = obj.dir_def == "" ? [] : obj.dir_def.split(splitStr);
  obj.except_app_type = obj.except_app_type == "" ? [] : obj.except_app_type.split(",");
  data.value = obj;
};
const delPath = (index) => {
  data.value.dir_def.splice(index, 1);
};
const setFileProtect = _debounce((params) => {
  if (!treeStore.treeDeviceId) return;
  req_setFileProtectConfig(treeStore.treeDeviceId, params).then((res) => {
    res.data.succeed ? ElMessage.success("设置成功") : ElMessage.error("设置失败");
    flag.value = false;
    getFileProtectionConfig();
  });
}, 500);
const paramsData = computed(() => {
  let params = {};
  params.data_def = data.value.data_def;

  let newArr = [];
  for (let i = 0; i < data.value.dir_def.length; i++) {
    if (!newArr.includes(data.value.dir_def[i])) {
      newArr.push(data.value.dir_def[i]);
    }
  }
  if (treeStore.osType === "linux" && newArr.length > 3) {
    ElMessage.error("最多只可以添加3个保护目录");
    getFileProtectionConfig();
    flag.value = false;
  }
  let splitStr = treeStore.osType === "linux" ? "," : ";";
  params.dir_def = newArr.join(splitStr);
  params.except_app_type = data.value.except_app_type.join(",");
  return params;
});
let flag = ref(false);
watch(
  paramsData,
  (val, oldVal) => {
    let params = [];
    for (var k in val) {
      if (val[k] !== oldVal[k]) {
        params.push({
          key: k,
          value: val[k],
        });
      }
    }
    // if (!treeStore.treeDeviceId) {
    //   ElMessage.error("未选择设备，请选择左侧分组中的设备后尝试");
    //   return;
    // }
    if (flag.value) setFileProtect(params);
  },
  {
    deep: true,
  }
);
</script>
<style lang="scss" scoped>
.content {
  padding: 20px 0;
  background-color: #fff;
  box-shadow: 0px 2px 4px 0px rgba(64, 32, 224, 0.06);
}
:deep(.el-select) {
  width: 310px;
}
.spanSty {
  background: rgba(0, 0, 0, 0.25);
  margin: 5px;
  display: table;
  border-color: #e9e9eb;
  border-radius: 2px;
  padding: 3px;
  font-weight: 400;
  color: rgba(255, 255, 255, 1);
}

.leftCont {
  width: 8%;
  text-align: right;
  margin-right: 16px;
  font-size: 16px;
}

.baseDiv {
  width: 400px;
  height: 110px;
  margin-right: 16px;
  background: #ffffff;
  border-radius: 2px;
  background: rgba(0, 0, 0, 0.1);
  overflow: auto;
  font-size: 16px;
}

.promptFont {
  font-size: 14px;
  font-family: SourceHanSansCN-Light;
  font-weight: 400;
  color: #999999;
  margin-left: 5px;
}
.file-type-err {
  font-size: 12px;
  color: red;
}
:deep(.el-select__wrapper) {
  font-size: 16px;
}
</style>
